#include "mazeview.h"
#include <QPainter>

MazeView::MazeView(IMazeModel* model, int viewCellSize, QObject *parent)
    : QObject(parent)
    , QGraphicsItem()
    , m_model(model)
    , m_cell_size(viewCellSize)
    , m_width(model->width()   * viewCellSize)
    , m_height(model->height() * viewCellSize)
{

}

MazeView::~MazeView(){ }

int MazeView::width() const{return m_width;}

int MazeView::height() const{return m_height;}

void MazeView::showPointStart(QPoint start)
{
    m_points.clear();
    m_points.push_back(start);
}

void MazeView::showPointStop(QPoint stop)
{
    while(m_points.size() > 1) m_points.pop_back();
    m_points.push_back(stop);
}

void MazeView::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    // draw grid
    for (int x = 0; x <= m_width; x += m_cell_size)
        painter->drawLine(x, 0, x, m_height);

    for (int y = 0; y <= m_height; y += m_cell_size)
        painter->drawLine(0, y, m_width, y);

    // draw maze blocks
    painter->setBrush(Qt::SolidPattern);
    for(auto &it : m_model->blocks())
        painter->drawRect(it.x() * m_cell_size, it.y() * m_cell_size, m_cell_size, m_cell_size);

    // draw start and stop points
    QPoint offset = QPoint(m_cell_size, m_cell_size) / 2;
    painter->setPen(QPen(Qt::red, 20));

    for(auto &it : m_points)
        painter->drawPoint(it * m_cell_size + offset);

    // draw points
    for(int i = 1; i < m_model->path().size(); ++i)
        painter->drawLine(m_model->path()[i-1] * m_cell_size + offset, m_model->path()[i] * m_cell_size + offset);

    Q_UNUSED(option);
    Q_UNUSED(widget);
}

QRectF MazeView::boundingRect() const
{
    return QRect(this->x(), this->y(), m_width, m_height);
}
